import request from '@/utils/request'

export function postAction(url, parameter) {
  return request({
    url: url,
    method: 'post',
    data: parameter,
  })
}

export function httpAction(url, parameter, method) {
  return request({
    url: url,
    method: method,
    data: parameter,
  })
}

export function putAction(url, parameter) {
  return request({
    url: url,
    method: 'put',
    data: parameter,
  })
}

export function getAction(url, parameter) {
  return request({
    url: url,
    method: 'get',
    params: parameter,
  })
}

export function downloadAction(url, method, parameter, filename) {
  return request({
    url: url,
    method: method,
    params: method === 'POST' ? '' : parameter,
    data: parameter,
    responseType: 'blob',
  })
    .then((response: any) => {
      const blobURL = window.URL.createObjectURL(response) // 将blob对象转为一个URL
      const tempLink = document.createElement('a') // 创建一个a标签
      tempLink.style.display = 'none'
      tempLink.href = blobURL
      tempLink.setAttribute('download', filename) // 给a标签添加下载属性
      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank')
      }
      document.body.appendChild(tempLink) // 将a标签添加到body当中
      tempLink.click() // 启动下载
      document.body.removeChild(tempLink) // 下载完毕删除a标签
      window.URL.revokeObjectURL(blobURL)
    })
    .catch((error) => {
      console.log(error)
    })
}

export function deleteAction(url, parameter) {
  return request({
    url: url,
    method: 'delete',
    params: parameter,
  })
}

export function postActionUpload(url, parameter, file) {
  return request({
    url: url,
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    onUploadProgress: (progressEvent) => {
      const percent = ((progressEvent.loaded / progressEvent.total) * 100) | 0
      // 调用onProgress方法来显示进度条，需要传递个对象 percent为进度值
      file.onProgress({ percent: percent })
    },
    data: parameter,
  })
}
